import urllib2, json

class RestClient:
    
    def __init__(self, host="localhost", port=8080, options=None):
        self.host = host
        self.port = port

    def __connect(self, uri):
        '''Returns the urllib2.Request object to connect to'''
        full_url = ''.join(['http://', self.host, ':', str(self.port), uri])
        print full_url
        return urllib2.Request(full_url)
    
    def get(self, uri):
        r = self.__connect(uri)
        r.add_header('Accept', 'application/json')
        c = urllib2.urlopen(r)
        try:
            return json.loads(c.read())
        except:
            return {}
 
    def post(self, uri, body):
        r = self.__connect(uri)
        r.add_header('Content-type', 'application/json')
        r.add_data(body)
        c = urllib2.urlopen(r)
        try:
            return json.loads(c.read())
        except:
            return {}
 
    def put(self, uri, body):
        r = self.__connect(uri)
        if len(body) > 0:
            r.add_header('Content-type', 'application/json')
            r.get_method = lambda: "PUT"
        else:
            r.get_method = lambda: "PUT"
        r.add_data(body)
        c = urllib2.urlopen(r)
        try:
            return json.loads(c.read())
        except:
            return {}
 
    def delete(self, uri):
        r = self.__connect(uri)
        r.get_method = lambda: 'DELETE'
        c = urllib2.urlopen(r)
        try:
            return json.loads(c.read())
        except:
            return {}